<?php
/**
 * 来访单位模型
 *
 */
class Model_Visitor extends Model_base{
	
	// 用户表名
	private $userTable ='';
	private $departmentTable ='';
	private $visitorTable ='';
	
	/**
	 * 构造函数
	 *
	 */
	public function __construct(){
		parent::__construct();
		$this->userTable = tabname('user');
		$this->departmentTable = tabname('department');
		$this->visitorTable = tabname('visitor');
	}
	
	

	public function countVisitor(){
		return $this->db->count($this->visitorTable,array('is_deleted'=>0));
	}
	
	public function listVisitor($start=null,$length=null){
		$sql = "select * from ".$this->visitorTable." WHERE is_deleted = 0";
		if($length > 0){
			$sql .= " limit $start,$length";
		}
		$lists = $this->db->fetchAll($sql);
		foreach ($lists as $key=>$row){
			$lists[$key]['text'] = $row['name'];
		}
		return $lists;
	}
	
	public function addVisitor($name){
		$sets_arr = array(
		         		'name'=>$name,
		         	);
		if($this->db->count($this->visitorTable,$sets_arr)){
			return false;
		}elseif(empty($name)){
			return false;
		}else{
			$this->db->insert($this->visitorTable,$sets_arr);
			$dept_id = $this->db->lastInsertId();
			if($dept_id>0){
				return true;
			}
			else{
				return false;
			}
		}
	}
	
	public function updateVisitor($id,$name){
		$sets_arr = array(
			'name'=>$name,
		);
		$where = "name = '".$name."' AND id != ".$id;
		if(empty($name) || empty($id)){
			return false;
		}elseif($this->db->count($this->visitorTable,$where)){
			return false;
		}else{
			$ret = $this->db->update($this->visitorTable,$sets_arr,array('id'=>$id));
			if($ret){
				return true;
			}
			else{
				return false;
			}
		}
	}
	
	public function delVisitor($id){
		if(empty($id)){
			return false;
		}else{
			$ret = $this->db->update($this->visitorTable,array('is_deleted'=>1),array('id'=>$id));
			if($ret){
				return true;
			}
			else{
				return false;
			}
		}
	}
}